'use strict'
export default function () {
  const w = this

  w.WW = window.innerWidth
  w.HH = window.innerHeight
  w.img

  const canvas = document.getElementById('canvas'),
      pr = window.devicePixelRatio

  canvas.width = w.WW * pr
  canvas.height = w.HH * pr

  let mW = 368,
      mH = 226,
      sX = (w.WW - mW) / 2 >> 0,
      sY = (w.HH - mH) / 2 >> 0,
      r = 60,
      bgc = 'rgb(40, 44, 52)',
      s_x = sX + 4,
      s_y = sY + mH / 2,
      e_x = sX + mW - 3,
      e_y = s_y,
      b_y = mH / 2

  let ctx = canvas.getContext('2d')
  ctx.scale(pr, pr)

  // prospect canvas
  let prospect = document.createElement('canvas'),
      pctx = prospect.getContext('2d')

  prospect.width = w.WW
  prospect.height = w.HH
  document.body.appendChild(prospect)

  w._init = () => {
    w.load('./eye.svg', w._movePoint)
    setInterval(()=> w._bink(600), 5000)
  }

  w._createPoint = (e) => {
    let x = ((w.WW - mW + 2 * r) / 2) + e.clientX / (w.WW / (mW - 2 * r))
    let y = ((w.HH - mH + 2 * r) / 2) + e.clientY / (w.HH / (mH - 2 * r))

    ctx.beginPath()
    ctx.fillStyle = '#FF0000'
    ctx.arc(x, y, r, 0, Math.PI * 2, true)
    ctx.fill()
    ctx.drawImage(w.img, 0, 0, mW, mH, sX, sY, mW, mH)

    ctx.beginPath()
    ctx.moveTo(s_x, s_y)
    ctx.bezierCurveTo(
        s_x + y * .2, y - b_y,
        e_x - y * .2, y - b_y,
        e_x, e_y)
    ctx.lineTo(e_x, sY)
    ctx.lineTo(s_x, sY)
    ctx.closePath()
    ctx.fillStyle = bgc
    ctx.fill()

    ctx.beginPath()
    ctx.moveTo(s_x, s_y)
    ctx.bezierCurveTo(
        s_x + y * .2, y + b_y,
        e_x - y * .2, y + b_y,
        e_x, e_y)
    ctx.fillStyle = bgc
    ctx.lineTo(e_x, sY + mH)
    ctx.lineTo(s_x, sY + mH)
    ctx.closePath()
    ctx.fill()
  }

  w._bink = (step) => {
    let startTime = Date.now(),
        distance = (b_y - s_y) * .8

    window.requestAnimationFrame(function bink() {
      let p = Math.min(1.0, (Date.now() - startTime) / step)
      let s = distance * 2 * Math.sin(2 * Math.PI * p)

      pctx.clearRect(0, 0, w.WW, w.HH)
      pctx.beginPath()
      pctx.moveTo(s_x, s_y)
      pctx.bezierCurveTo(
          s_x, s_y + distance - s,
          e_x, s_y + distance - s,
          e_x, e_y)
      pctx.lineTo(e_x, sY)
      pctx.lineTo(s_x, sY)
      pctx.closePath()
      pctx.fillStyle = bgc
      pctx.fill()

      if (p < 1.0) requestAnimationFrame(bink)
    })
  }

  w._createBackground = () => {
    ctx.beginPath()
    ctx.rect(sX, sY, mW, mH);
    ctx.fillStyle = '#fff'
    ctx.fill()
  }

  w._movePoint = () => {
    window.addEventListener('mousemove', (e) => {
      ctx.clearRect(0, 0, w.WW, w.HH)
      w._createBackground()
      w._createPoint(e)
    }, false)
  }

  w.load = (url, callback) => {
    let img = new Image()
    img.src = url
    img.onload = () => {
      w.img = img
      callback()
    }
  }

  w._init()
}
